﻿using CrmField.Win8App.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Search Contract item template is documented at http://go.microsoft.com/fwlink/?LinkId=234240

namespace CrmField.Win8App
{
    /// <summary>
    /// This page displays search results when a global search is directed to this application.
    /// </summary>
    public sealed partial class SearchResultsPage : CrmField.Win8App.Common.LayoutAwarePage
    {

        public SearchResultsPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            var queryTextParam= navigationParameter as String;
            string queryText = string.IsNullOrEmpty(queryTextParam) ? string.Empty : queryTextParam.ToLowerInvariant(); 
            
            var filterList = new List<Filter>();
            Filter firstFilterAllAppointments = new Filter("All", null, true);
            filterList.Add(firstFilterAllAppointments);
            int filterCount = 0;
            int allAppointmentFilterCount = 0;
            ObservableCollection<ServiceAppointment> filteredAppointments;
            List<ServiceAppointment> allFilteredAppointments = new List<ServiceAppointment>();
            foreach (ActivityDataGroup appointmentGroup in ActivityDataSource.CurrentDataSource.AllGroups)
            {
                filteredAppointments = new ObservableCollection<ServiceAppointment>(from a in appointmentGroup.Items 
                                                                                    where !string.IsNullOrEmpty(a.Subject) &&
                                                                                        a.Subject.ToLowerInvariant().Contains(queryText) 
                                                                                    select a);
                filterCount = filteredAppointments.Count;
                if (filterCount > 0)
                {
                    allFilteredAppointments.AddRange(filteredAppointments);
                    filterList.Add(new Filter(appointmentGroup.FormatedDate, filteredAppointments));
                    allAppointmentFilterCount += filterCount;
                    filterCount = 0;
                }
            };

            firstFilterAllAppointments.FilteredResult = allFilteredAppointments;

            // Communicate results through the view model
            this.DefaultViewModel["QueryText"] = '\u201c' + queryText + '\u201d';
            this.DefaultViewModel["Filters"] = filterList;
            this.DefaultViewModel["ShowFilters"] = filterList.Count > 1;
        }

        /// <summary>
        /// Invoked when a filter is selected using the ComboBox in snapped view state.
        /// </summary>
        /// <param name="sender">The ComboBox instance.</param>
        /// <param name="e">Event data describing how the selected filter was changed.</param>
        void Filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Determine what filter was selected
            var selectedFilter = e.AddedItems.FirstOrDefault() as Filter;
            if (selectedFilter != null)
            {
                // Mirror the results into the corresponding Filter object to allow the
                // RadioButton representation used when not snapped to reflect the change
                selectedFilter.Active = true;

                this.DefaultViewModel["Results"] = selectedFilter.FilteredResult;

                // Ensure results are found
                object results;
                ICollection resultsCollection;
                if (this.DefaultViewModel.TryGetValue("Results", out results) &&
                    (resultsCollection = results as ICollection) != null &&
                    resultsCollection.Count != 0)
                {
                    VisualStateManager.GoToState(this, "ResultsFound", true);
                    return;
                }
            }

            // Display informational text when there are no search results.
            VisualStateManager.GoToState(this, "NoResultsFound", true);
        }

        /// <summary>
        /// Invoked when a filter is selected using a RadioButton when not snapped.
        /// </summary>
        /// <param name="sender">The selected RadioButton instance.</param>
        /// <param name="e">Event data describing how the RadioButton was selected.</param>
        void Filter_Checked(object sender, RoutedEventArgs e)
        {
            // Mirror the change into the CollectionViewSource used by the corresponding ComboBox
            // to ensure that the change is reflected when snapped
            if (filtersViewSource.View != null)
            {
                var filter = (sender as FrameworkElement).DataContext;
                filtersViewSource.View.MoveCurrentTo(filter);
            }
        }

        /// <summary>
        /// Invoked when an item within a group is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var itemId = ((ServiceAppointment)e.ClickedItem).ActivityId;
            this.Frame.Navigate(typeof(ItemDetailPage), itemId);
        }

        /// <summary>
        /// View model describing one of the filters available for viewing search results.
        /// </summary>
        private sealed class Filter : CrmField.Win8App.Common.BindableBase
        {
            private String _name;
            private int _count;
            private bool _active;
            private IEnumerable<ServiceAppointment> _filteredResult;

            public Filter(String name, IEnumerable<ServiceAppointment> filteredResult, bool active = false)
            {
                this.Name = name;
                this.Active = active;
                this.FilteredResult = filteredResult;
            }

            public IEnumerable<ServiceAppointment> FilteredResult 
            {
                get { return _filteredResult; }
                set
                {
                    if (this.SetProperty(ref _filteredResult, value))
                    {
                        if (value != null)
                            _count = value.Count();
                        else
                            _count = 0;
                        this.OnPropertyChanged("Description");
                    }
                }
            }

            public override String ToString()
            {
                return Description;
            }

            public String Name
            {
                get { return _name; }
                set { if (this.SetProperty(ref _name, value)) this.OnPropertyChanged("Description"); }
            }

            public int Count
            {
                get 
                {
                    return _count; 
                }
            }

            public bool Active
            {
                get { return _active; }
                set { this.SetProperty(ref _active, value); }
            }

            public String Description
            {
                get { return String.Format("{0} ({1})", _name, _count); }
            }
        }
    }
}
